package goComfyuiApi

import (
	"fmt"
	"io"
	"net/http"

	"gitee.com/wchpub/fnsvr"
)

// 下载图片
func ApiDownloadWorkflowImage(comfyuiUrl, filename, subfolder string) ([]byte, error) {
	url := genComfyUIApiUrl(comfyuiUrl, "view")
	urlParam := fmt.Sprintf("?filename=%s&subfolder=%s&type=output&t=%d", filename, subfolder, fnsvr.GetMilliTimestamp())

	resp, err := http.Get(url + urlParam)
	if err != nil {
		return nil, fmt.Errorf("failed to download image: %v", err)
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("image download failed with status: %s", resp.Status)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response body: %v", err)
	}

	return body, nil
}
